<template>
  <!-- 在页面顶部或底部添加加载遮罩 -->
  <div v-loading="submitting" class="inventory-assembler-detail-container">
    <div class="inventory-assembler-detail-container">
      <!-- Document Information Group -->
      <el-card class="info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <div class="title-wrapper">
              <span class="title-text">单据信息</span>
              <span v-if="supportMultyStore" class="store-name">{{ inventoryAssembler.storeName }}</span>
              <el-tag v-if="!this.editMode"
                :type="inventoryAssembler.status.code === CommonOrderStatus.Passed.code ? 'success' : 'info'"
                size="small" class="status-tag">
                {{ inventoryAssembler.status.name }}
              </el-tag>
            </div>
            <!-- Action Buttons -->
            <div class="action-buttons" v-if="!this.editMode">
              <el-button plain @click="handleCopy">
                <el-icon>
                  <CopyDocument />
                </el-icon> 复制
              </el-button>
              <el-button plain @click="handlePrint" style="margin-right: 20px">
                <el-icon>
                  <Printer />
                </el-icon> 打印
              </el-button>
              <el-button type="primary" plain @click="handleEdit">
                <el-icon>
                  <Edit />
                </el-icon> 编辑
              </el-button>
              <el-button type="danger" plain @click="handleDelete">
                <el-icon>
                  <Delete />
                </el-icon> 删除
              </el-button>
            </div>
          </div>
        </template>
        <el-form ref="ruleFormRef" :model="formData" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="6">
              <input-widget-web v-model="formData.title" label="单据标题" prop="title" :readonly="!this.editMode" />
            </el-col>
            <el-col v-if="!this.editMode" :span="6">
              <input-widget-web v-model="formData.docCode" label="单据编号" prop="docCode" :readonly="!this.editMode" />
            </el-col>

            <el-col :span="6">
              <date-time-select v-model="formData.operateDate" label="盘点分类日期" prop="operateDate"
                :readonly="!this.editMode" type="datetime" />
            </el-col>

            <el-col :span="6">
              <input-widget-web v-model="formData.cost" label="盘点分类费" prop="cost" :readonly="!this.editMode"
                :numberMode="true" :precision="costNumPrecision" :isFundType="true" />
            </el-col>

            <el-col :span="6">
              <employee-select v-model="formData.operator" label="经办人" prop="operator" :readonly="!this.editMode"
                :enterpriseMgtUiAction="enterpriseMgtUiAction" />
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <!-- 源商品 Source Items Group -->
      <el-card class="items-card" shadow="never">
        <template #header>
          <div class="card-header">
            <div class="title-wrapper">
              <div class="summary-container">
                <span class="title-text">源商品</span>
                <span class="total-info">
                  共{{ inventoryAssembler.srcCommodityQuantity }}件
                </span>
              </div>

              <!-- 仓库 -->
              <warehouse-select v-if="supportMultyWarehouse" style="padding-top: 20px; padding-left: 20px;"
                v-model="formData.srcWarehouse" label="出库仓库" prop="srcWarehouse" :readonly="!this.editMode"
                :inventoryUiAction="inventoryUiAction" />

              <!-- 添加和删除按钮 -->
              <div v-if="editMode" class="action-buttons">
                <el-button type="primary" size="small" @click="handleAddSourceCommodity">
                  添加商品
                </el-button>
                <el-button type="danger" size="small" @click="handleDeleteSelectedSourceCommodities">
                  删除商品
                </el-button>
              </div>

            </div>
          </div>
        </template>

        <el-table :data="inventoryAssembler.orgCommodityList" style="width: 100%"
          @selection-change="handleSourceSelectionChange">
          <!-- 勾选列 -->
          <el-table-column type="selection" width="55" v-if="editMode" />
          <el-table-column label="图片" width="150">
            <template #default="scope">
              <el-image v-if="scope.row.commodity.imgs" :src="scope.row.commodity.imgs.split(',')[0]" fit="cover"
                class="commodity-image"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" width="180">
            <template #default="scope">
              {{ scope.row.commodity.name }}
            </template>
          </el-table-column>
          <el-table-column label="规格" width="180">
            <template #default="scope">
              {{ scope.row.commodity.standard }}
            </template>
          </el-table-column>
          <el-table-column label="单位" width="80">
            <template #default="scope">
              {{ scope.row.commodity.unit?.name || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="数量" align="right" width="100">
            <template #default="scope">
              <quality-input-cell v-if="false" :commodityBatch="scope.row" :decimalAllowed="true" />
              <span v-else>{{ formatCount(scope.row.count.value) }}</span>
            </template>
          </el-table-column>

        </el-table>
      </el-card>

      <!-- Target Items Group -->
      <el-card class="items-card" shadow="never">
        <template #header>
          <div class="card-header">
            <div class="title-wrapper">
              <div class="summary-container">
                <span class="title-text">目标商品</span>
                <span class="total-info">
                  共{{ inventoryAssembler.newCommodityQuantity }}件
                </span>
              </div>

              <!-- 目标仓库 -->
              <warehouse-select v-if="supportMultyWarehouse" style="padding-top: 20px; padding-left: 20px;"
                v-model="formData.targetWarehouse" label="入库仓库" prop="targetWarehouse" :readonly="!this.editMode"
                :inventoryUiAction="inventoryUiAction" />

              <!-- 添加和删除按钮 -->
              <div v-if="editMode" class="action-buttons">
                <el-button type="primary" size="small" @click="handleAddTargetCommodity">
                  添加商品
                </el-button>
                <el-button type="danger" size="small" @click="handleDeleteSelectedTargetCommodities">
                  删除商品
                </el-button>
              </div>

            </div>
          </div>
        </template>

        <el-table :data="inventoryAssembler.newCommodityList" style="width: 100%"
          @selection-change="handleTargetSelectionChange">
          <!-- 勾选列 -->
          <el-table-column type="selection" width="55" v-if="editMode" />
          <el-table-column label="图片" width="150">
            <template #default="scope">
              <el-image v-if="scope.row.commodity.imgs" :src="scope.row.commodity.imgs.split(',')[0]" fit="cover"
                class="commodity-image"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" width="180">
            <template #default="scope">
              {{ scope.row.commodity.name }}
            </template>
          </el-table-column>
          <el-table-column label="规格" width="180">
            <template #default="scope">
              {{ scope.row.commodity.standard }}
            </template>
          </el-table-column>
          <el-table-column label="单位" width="80">
            <template #default="scope">
              {{ scope.row.commodity.unit?.name || '-' }}
            </template>
          </el-table-column>



          <el-table-column label="数量" align="right" width="100">
            <template #default="scope">
              <quality-input-cell v-if="editMode" :commodityBatch="scope.row" :decimalAllowed="true" />
              <span v-else>{{ formatCount(scope.row.count.value) }}</span>
            </template>
          </el-table-column>

        </el-table>
      </el-card>

      <!-- Other Information Group -->
      <el-card class="other-info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <div class="title-wrapper">
              <span class="title-text">其他信息</span>
            </div>
          </div>
        </template>

        <el-descriptions v-if="!editMode" :column="1">
          <el-descriptions-item v-if="latestUpdateInfo" label="最近更新">{{ latestUpdateInfo
          }}</el-descriptions-item>
          <el-descriptions-item label="制单人">{{ docMaker }}</el-descriptions-item>
          <el-descriptions-item label="备注">
            <div class="remark-content">{{ inventoryAssembler.remark || '-' }}</div>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 备注 -->
        <input-widget-web v-if="editMode" v-model="formData.remark" label="备注" prop="remark" placeholder="请输入备注信息"
          :remarkMode="true" />
      </el-card>

      <!-- 底部操作栏 (仅在编辑模式下显示) -->
      <bottom-bar :visible="editMode">
        <template #left>
          <span class="doc-maker-info">制单人: {{ docMakerBottmBar }}</span>
        </template>
        <template #right>
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </template>
      </bottom-bar>

      <!-- 商品选择弹窗 -->
      <subcommodity-select-dialog ref="commoditySelectDialog" :basic-ui-action="basicUiAction"
        @select="handleCommoditySelect" />
    </div>
  </div>
</template>
<script>
import { InventoryAssembler } from '../../public/engine/inventory/inventoryAssembler';
import { Employee } from '../../public/engine/enterpriseMgt/employee'
import { InventoryUiAction } from '../../public/engine/uiAction/inventoryUiAction';
import { CommonOrderStatus } from '../../public/engine/common/docDefinition';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Util } from '../../public/utils/util';
import { DateUtil } from '../../public/utils/dateUtil';
import EventBus from '../../public/engine/ipc/eventBus';
import WarehouseSelect from '../../public/views/componentsWeb/WarehouseSelect.vue';
import InputWidgetWeb from '../../public/views/componentsWeb/InputWidgetWeb.vue';
import EmployeeSelect from '../../public/views/componentsWeb/EmployeeSelect.vue';
import QualityInputCell from '../../public/views/componentsWeb/QualityInputCell.vue';
import SinglePriceInputCell from '../../public/views/componentsWeb/SinglePriceInputCell.vue';
import TotalPriceInputCell from '../../public/views/componentsWeb/TotalPriceInputCell.vue';
import SubcommoditySelectDialog from '../../views/inventory/subcommoditySelectDialog.vue';
import BottomBar from '../../public/views/componentsWeb/BottomBar.vue';
import { CommodityBatch } from '../../public/engine/inventory/inventory';
import { CsDouble } from '../../public/engine/common/csDouble';
import { BasicUiAction } from '../../public/engine/uiAction/basicUiAction';
import { EnterpriseMgtUiAction } from '../../public/engine/uiAction/enterpriseMgtUiAction';
import DateTimeSelect from '../../public/views/componentsWeb/DateTimeSelect.vue'
import { CsFundDouble } from '../../public/engine/common/csFundDouble';
import { ActionResult, ActionResultType } from '../../public/engine/common/actionResult';
import { Definition } from '../../public/engine/common/definition';
import { MessageUtil } from '../../utils/messageUtil';
import TabUtil from '@/plugins/tab'
import { Engine } from '../../public/engine/engine'


export default {
  name: "assembler",
  components: {
    WarehouseSelect,
    InputWidgetWeb,
    EmployeeSelect,
    QualityInputCell,
    SinglePriceInputCell,
    TotalPriceInputCell,
    SubcommoditySelectDialog,
    BottomBar,
    DateTimeSelect
  },
  data() {
    return {
      inventoryAssembler: InventoryAssembler.empty(),
      orgInventoryAssembler: InventoryAssembler.empty(),
      inventoryUiAction: new InventoryUiAction(),
      basicUiAction: new BasicUiAction(),
      enterpriseMgtUiAction: new EnterpriseMgtUiAction(),
      loading: false,
      editMode: false,
      orderId: "",
      formData: {
        docCode: '', // 添加此初始化
        title: '',
        operateDate: null,
        operator: null,
        remark: '',
        srcWarehouse: null,
        targetWarehouse: null,
        cost: 0
      },
      // 返回数据
      retValue: null,
      orgSelectedCommodities: [], // 源选中商品
      targetSelectedCommodities: [],  // 目标选中商品
      submitting: false,
      CommonOrderStatus,
      isOrgCommoditySelecting: null,  // true 源商商品选择中， false 新商品选择中 other 异常

    };
  },
  mounted() {
    this.orderId = (this.$route.params.id || this.$route.query.id) || "";
    if (!Util.isEmpty(this.orderId)) {
      this.loadInventoryData();
    } else {
      this.editMode = true;
      this.syncFormData();
    }
  },
  beforeUnmount() {
    EventBus.emit('inventoryAssemblerUpdated', null);
  },
  computed: {
    latestUpdateInfo() {
      return (this.inventoryAssembler.updateor && this.inventoryAssembler.updateDate) ?
        (this.inventoryAssembler.updateor + "  " + DateUtil.getDayTitle(this.inventoryAssembler.updateDate)) : null;
    },
    docMaker() {
      return (this.inventoryAssembler.id && this.inventoryAssembler.docMaker && this.inventoryAssembler.recordDate) ?
        (this.inventoryAssembler.docMaker + "  " + DateUtil.getDayTitle(this.inventoryAssembler.recordDate)) : null
    },

    costNumPrecision() {
      return Definition.fundPrecision;
    },

    docMakerBottmBar() {
      return Engine.profile?.nickName.isEmpty
        ? Engine.profile?.userName
        : Engine.profile?.nickName;
    },

    // 支持多仓库
    supportMultyWarehouse() {
      return Engine.getOrgSettings().enableMultiWarehouse;
    },

    // 支持多门店
    supportMultyStore() {
      return Engine.getOrgSettings().multiStoreMode;
    },

  },
  methods: {
    syncFormData() {
      this.formData = {
        docCode: this.inventoryAssembler.docCode,
        title: this.inventoryAssembler.title,
        operateDate: this.inventoryAssembler.operateDate,
        operator: new Employee({ id: this.inventoryAssembler.operatorId, name: this.inventoryAssembler.operator }),
        remark: this.inventoryAssembler.remark,
        srcWarehouse: this.inventoryAssembler.srcWareHouse,
        targetWarehouse: this.inventoryAssembler.targetWareHouse,
        cost: this.inventoryAssembler.cost.value,
        //
        updator: (this.inventoryAssembler.updateor && this.inventoryAssembler.updateDate) ?
          (this.inventoryAssembler.updateor + "  " + DateUtil.getDayTitle(this.inventoryAssembler.updateDate)) : null,
        docMaker: (this.inventoryAssembler.id && this.inventoryAssembler.docMaker && this.inventoryAssembler.recordDate) ?
          (this.inventoryAssembler.docMaker + "  " + DateUtil.getDayTitle(this.inventoryAssembler.recordDate)) : null,
      };
    },
    fillWithFormData() {
      this.inventoryAssembler.title = this.formData.title;
      // formData.operateDate 控件变更日期会转换为字符串，这里需要转换回Date对象
      if (!(this.formData.operateDate instanceof Date)) {
        this.inventoryAssembler.operateDate = DateUtil.strToDate(this.formData.operateDate);
      } else {
        this.inventoryAssembler.operateDate = this.formData.operateDate;
      }
      this.inventoryAssembler.setOperator({ operator: this.formData.operator.name, operatorId: this.formData.operator.id });
      this.inventoryAssembler.remark = this.formData.remark;
      this.inventoryAssembler.srcWareHouse = this.formData.srcWarehouse;
      this.inventoryAssembler.targetWareHouse = this.formData.targetWarehouse;
      this.inventoryAssembler.cost = new CsFundDouble(this.formData.cost);
    },
    async loadInventoryData() {
      try {
        this.loading = true;
        const res = await this.inventoryUiAction.getInventoryAssemblerDetailInfo(this.orderId);
        if (res) {
          console.log('got inventoryAssembler:', res);
          this.inventoryAssembler = res;
          this.orgInventoryAssembler = InventoryAssembler.clone(res);
          this.syncFormData();
        } else {
          ElMessage.error("加载盘点分类单详情失败");
        }
      } catch (error) {
        console.error("加载盘点分类单详情失败", error);
        ElMessage.error("加载盘点分类单详情失败");
      } finally {
        this.loading = false;
      }
    },
    handleCopy() {
      this.inventoryAssembler = InventoryAssembler.clone(this.inventoryAssembler);
      this.inventoryAssembler.id = '';
      this.editMode = true;
      ElMessage.success("复制完成");
    },
    async handleDelete() {
      if (Util.isEmpty(this.inventoryAssembler.id)) {
        TabUtil.closePage();
      } else {

        try {
          await ElMessageBox.confirm("确定要删除该盘点分类单吗？", "删除确认", {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          });
          this.submitting = true;
          const delResult = await this.inventoryUiAction.removeInventoryAssemberOrder({
            orderId: this.inventoryAssembler.id,
            docType: this.inventoryAssembler.docType
          });
          if (delResult == null) {
            this.retValue = new ActionResult({ type: ActionResultType.Del })
            MessageUtil.showSuccessMsg("删除成功");
            TabUtil.closePage();
          }
        } catch (error) {
          if (error !== 'cancel') {
            console.error("inventoryAssebler handleDelete error:", error);
            ElMessage.error("删除操作失败");
          }
        }
        finally {
          this.loading = false;
        }
      }
    },
    handleEdit() {
      this.editMode = true;
    },
    handleCancel() {
      this.inventoryAssembler = InventoryAssembler.clone(this.orgInventoryAssembler);
      this.editMode = false;
    },
    async handleSubmit() {
      this.submitting = true;
      try {
        this.fillWithFormData();
        const validationError = this.inventoryAssembler.validateOrder();
        if (validationError) {
          ElMessage.error(validationError);
          return;
        }
        const orderResult = await this.inventoryUiAction.updateOrCreateInventoryAssembler(this.inventoryAssembler, true);
        if (orderResult) {
          if (Util.isEmpty(this.inventoryAssembler.id)) {
            this.retValue = new ActionResult({ type: ActionResultType.New })
          }
          else {
            this.retValue = new ActionResult({ type: ActionResultType.UpdateCommon })
          }
        }

        if (orderResult) {
          // 刷新订单页面
          ElMessage.success("提交保存成功");

          this.orderId = orderResult.id;
          this.editMode = false;
          this.loadInventoryData();
        }

      } catch (error) {
        console.error("保存失败", error);
        ElMessage.error("保存失败");
      } finally {
        this.submitting = false;
      }
    },

    /////////////////////////  源商品操作
    // 添加来源商品
    handleAddSourceCommodity() {

      if (this.formData.srcWarehouse == null || this.formData.srcWarehouse.id == null
        || Util.isEmpty(this.formData.srcWarehouse.id)
      ) {
        // 提示先选择出库仓库
        MessageUtil.showWarningMsg("请先选择出库仓库");
        return;
      }

      this.isOrgCommoditySelecting = true;

      this.$refs.commoditySelectDialog.open(this.inventoryAssembler.commodityList({ isOrgCommodity: true }),
        {
          //excludeCommodities: this.inventoryAssembler.commodityList({ isOrgCommodity: false }),
          warehouse: this.formData.srcWarehouse
        });
    },

    handleSourceSelectionChange(selection) {
      console.log("handleSourceSelectionChange", selection);
      this.orgSelectedCommodities = selection;
    },

    // 移除源商品
    handleDeleteSelectedSourceCommodities() {
      console.log("handleDeleteSelectedSourceCommodities");
      const isOrgCommodity = true;
      if (this.orgSelectedCommodities.length === 0) {
        ElMessage.warning('请至少选择一个商品进行删除');
        return;
      }
      this.orgSelectedCommodities.forEach(commodity => {
        this.inventoryAssembler.removeCommodityBatch(commodity, { isOrgCommodity });
      });
      this.orgSelectedCommodities = [];
    },

    /////////////////////////  目标商品操作

    // 添加来源商品
    handleAddTargetCommodity() {

      if (this.formData.targetWarehouse == null || this.formData.targetWarehouse.id == null
        || Util.isEmpty(this.formData.targetWarehouse.id)
      ) {
        // 提示先选择出库仓库
        MessageUtil.showWarningMsg("请先选择入库仓库");
        return;
      }

      this.isOrgCommoditySelecting = false;

      this.$refs.commoditySelectDialog.open(this.inventoryAssembler.commodityList({ isOrgCommodity: false }),
        {
          // excludeCommodities: this.inventoryAssembler.commodityList({ isOrgCommodity: true }),
          warehouse: this.formData.targetWarehouse
        }
      );
    },

    handleTargetSelectionChange(selection) {
      this.targetSelectedCommodities = selection;
    },

    // 移除源商品
    handleDeleteSelectedTargetCommodities() {
      const isOrgCommodity = false;
      if (this.targetSelectedCommodities.length === 0) {
        ElMessage.warning('请至少选择一个商品进行删除');
        return;
      }
      this.targetSelectedCommodities.forEach(commodity => {
        this.inventoryAssembler.removeCommodityBatch(commodity, { isOrgCommodity });
      });
      this.targetSelectedCommodities = [];
    },

    /////////////////////////  商品选择回调
    handleCommoditySelect(items) {
      console.log('handleCommoditySelect', items);
      items.forEach(commodity => {
        let batchIn = new CommodityBatch({
          commodity: commodity.subCommodity,
          availableCount: commodity.availableCount,
          inventoryCount: commodity.totalInventoryCount,
          count: this.isOrgCommoditySelecting ? new CsDouble(commodity.availableCount) : new CsDouble(1),
          batchPrice: commodity.subCommodity.retailPrice,
          singlePrice: commodity.subCommodity.retailPrice
        });

        const batch = this.inventoryAssembler.addOrUpdateCommodityBatch(batchIn, { isOrgCommodity: this.isOrgCommoditySelecting });
        if (batch) {
          ElMessage.warning(`商品[${commodity.subCommodity.name}]已存在，数量已累加`);
        }
      });
    },

    // 打印
    handlePrint() {

    },

    formatCount(value) {
      return Util.getCountString(value);
    },

    formatCurrency(value) {
      return Util.getFundString(value);
    },
  }
};
</script>

<style scoped>
.inventory-assembler-detail-container {
  padding: 20px;
  padding-bottom: 80px;
}

.info-card,
.items-card,
.other-info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-buttons {
  display: flex;
  gap: 12px;
  margin-bottom: 0px;
  padding: 0 16px;
}

/* 在现有样式中添加或修改 */
.title-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;
}

.commodity-image {
  width: 50px;
  height: 50px;
}

.total-info {
  margin-left: 20px;
  font-size: 14px;
  color: #666;
}
</style>